//
//  LoginVC.swift
//  DianXia
//
//  Created by you&me on 2017/12/15.
//  Copyright © 2017年 you&me. All rights reserved.
//

import UIKit

class LoginVC: UIViewController {

    @IBOutlet weak var phoneText: UITextField!
    @IBOutlet weak var phoneAlert: UILabel!
    @IBOutlet weak var phoneCode: UITextField!
    @IBOutlet weak var getCodeBtn: UIButton!
    @IBOutlet weak var applicationBtn: UIButton!
    @IBOutlet weak var backBtn: UIButton!

    let dispose = DisposeBag()
    let loginVM = LoginVM()

    override func viewDidLoad() {
        super.viewDidLoad()
        obserState()
    }

   fileprivate func obserState()  {
        // 手机号的观察转换
        let phoneState = phoneText.rx.text.orEmpty
                                  .map { $0.validateText(.PhoneNumber) }
                                  .share(replay: 1)
        // 和提示绑定 以及获取验证码按钮
        phoneState
                 .bind(to: phoneAlert.ex_AlertState)
                 .disposed(by: dispose)
        phoneState
                 .bind(to: getCodeBtn.ex_State)
                 .disposed(by: dispose)
        //验证码的转换
        let codeState = phoneCode.rx.text.orEmpty
                                 .map { $0.count == 5  }
                                 .share(replay: 1)
        //合成手机号和验证码的信号
        let comState = Observable.combineLatest(phoneState, codeState) { $0 && $1 }

        // 与登录按钮进行绑定
        comState.bind(to: applicationBtn.ex_State)
                .disposed(by: dispose)
        //获取验证码的操作 controlEvent 控制事件
       getCodeBtn.rx.tap
                    .subscribe({ [weak self] _ in self?.loginVM.getLoginPhoneCode(self?.phoneText.text ?? "" , "login") })
                    .disposed(by: dispose)

        // 登录按钮的点击事件
        applicationBtn.rx.tap
            .subscribe({ [weak self] _ in self?.loginVM.bcLogin(self?.phoneText.text ?? "", self?.phoneCode.text ?? "", {
                     self?.presenVC()
                 })
            })
            .disposed(by: dispose)

        // 返回按钮的点击事件
        backBtn.rx.tap
            .subscribe({ [weak self] _ in self?.dismiss(animated: true, completion: nil) })
            .disposed(by: dispose)

    }

    func presenVC() {
        let vc = UIStoryboard.initialViewControllerFromStoryboard(.Home) as! UIViewController
        self.present(vc, animated: true, completion: nil)
    }

}
